package com.cxh.controller.carInterface;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shimne.util.ObjectUtil;
import com.shimne.util.StringUtil;
import com.cxh.base.BaseController;
import com.cxh.controller.Thread.HttpThread;
import com.cxh.controller.robot.JsonAction;
import com.cxh.entity.CarCategory;
import com.cxh.entity.CarCompetitive;
import com.cxh.entity.CarCompetitiveDetail;
import com.cxh.entity.CarDetailBaseInfo;
import com.cxh.entity.CarDetailBody;
import com.cxh.entity.CarDetailChangeSpeedCase;
import com.cxh.entity.CarDetailChassisTurn;
import com.cxh.entity.CarDetailConditionRefrigerator;
import com.cxh.entity.CarDetailControlConfig;
import com.cxh.entity.CarDetailEngine;
import com.cxh.entity.CarDetailGlassMirror;
import com.cxh.entity.CarDetailHighTech;
import com.cxh.entity.CarDetailInConfig;
import com.cxh.entity.CarDetailLightConfig;
import com.cxh.entity.CarDetailMediaConfig;
import com.cxh.entity.CarDetailOutConfig;
import com.cxh.entity.CarDetailSafetyEquipment;
import com.cxh.entity.CarDetailSeatConfig;
import com.cxh.entity.CarDetailWheelBrake;
import com.cxh.entity.CarDiscount;
import com.cxh.entity.CarDiscountDetail;
import com.cxh.entity.CarLoan;
import com.cxh.entity.CarModel;
import com.cxh.entity.CarQuestion;
import com.cxh.entity.Constant;
import com.cxh.entity.RobotInfo;
import com.cxh.entity.SkillsOption;
import com.cxh.entity.SoundQu;
import com.cxh.util.ComUtil;
import com.cxh.util.CommonUtility;
import com.cxh.util.DateUtility;
import com.cxh.util.HttpUtil;
import com.cxh.util.LogUtil;
import com.cxh.util.StringUtils;
import com.cxh.util.json.JSONUtil;

@Controller
@RequestMapping("/controller/CarInterface")
public class CarInterfaceController extends BaseController{
	

	private String speak = "";// 返回语言
	private String url = "";
	private int msgType = 2; // 2默认 1.场景模式 2.对答模式 
	private String msg = "返回成功";	//日志说明
	private int flag = 0; // 返回标志
	private int scene = 0;	//场景类型
	private int skill = 0;
	private int status = 1;	//返回状态  0、匹配失败  1、匹配成功  2、未匹配到内容  3、匹配多项
	
	
	/**
	 * @类功能说明：汽车问卷调查接口
	 * @作者：Chenxh
	 * @创建时间：2018年11月15日上午11:57:08
	 */
	@RequestMapping("/carQuestionSurvey")
	@ResponseBody
	public String carQuestionSurvey(HttpServletRequest request, HttpServletResponse response){
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		//获得  页码数
        Integer page=CommonUtility.isEmpty(request.getParameter("page"))?1:Integer.parseInt(request.getParameter("page")+"");
        //获得 每页的行数
        Integer limit=CommonUtility.isEmpty(request.getParameter("limit"))?10:Integer.parseInt(request.getParameter("limit")+"");
		//开始价格
		String beginPrice = request.getParameter("beginPrice");
		//截止价格
		String endPrice = request.getParameter("endPrice");
		//变速箱
		String gear = request.getParameter("gear");
		//汽车车型
		String level = request.getParameter("level");
		//汽车排量
		String output = request.getParameter("output");
		//机器人编号
		String code = request.getParameter("code");
		long outputValue = 0;
		if(!CommonUtility.isEmpty(output)){
			outputValue = new BigDecimal(output.toString()).setScale( 0, BigDecimal.ROUND_DOWN ).longValue();// 向下取整
		}
		//进气形式
		String TOrL =  request.getParameter("TOrL");
		HashMap<String, Object> params = new HashMap<String,Object>();
		
		
		ArrayList<Map<String, String>> threadList = new ArrayList<Map<String, String>>();
		try {
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("智能导购", code);
			threadList.add(hashMap);
			//HttpThread.createThreadPoor(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode("智能导购","utf-8")+"&code="+code);
			//HttpUtil.post(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode("智能导购","utf-8")+"&code="+code, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//查询该车
		CarModel carModel = new CarModel();
		
		if(!CommonUtility.isEmpty(beginPrice)){
			carModel.setBeginPrice((new Double(Double.parseDouble(beginPrice))).intValue());
			params.put("beginPrice", beginPrice);
		}
		if(!CommonUtility.isEmpty(endPrice)){
			carModel.setEndPrice((new Double(Double.parseDouble(endPrice))).intValue());
			params.put("endPrice", endPrice);
		}
		if(!CommonUtility.isEmpty(beginPrice) && !CommonUtility.isEmpty(endPrice)){
			try {
				HashMap<String, String> hashMap = new HashMap<String, String>();
				hashMap.put(beginPrice+"到"+endPrice, code);
				threadList.add(hashMap);
				//HttpThread.createThreadPoor(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode(beginPrice+"到"+endPrice,"utf-8")+"&code="+code);
				//HttpUtil.post(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode(beginPrice+"到"+endPrice,"utf-8")+"&code="+code,"");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if(!CommonUtility.isEmpty(gear)){
			//自动挡查询的是手动挡，手动挡查询的是自动挡
			carModel.setGearbox(gear.equals("自动挡")?"手动挡":gear);
			try {
				HashMap<String, String> hashMap = new HashMap<String, String>();
				hashMap.put(gear.equals("自动挡")?"手动挡":gear, code);
				threadList.add(hashMap);
				//HttpThread.createThreadPoor(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode((gear.equals("自动挡")?"手动挡":gear),"utf-8"));
				//gear = gear.equals("自动挡")?"手动挡":gear;
				//HttpUtil.post(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode(gear,"utf-8")+"&code="+code,"");
			} catch (Exception e) {
				e.printStackTrace();
			}
			params.put("gearbox", gear);
		}
		
		if(!CommonUtility.isEmpty(level)){
			carModel.setLevel(level);
			try {
				HashMap<String, String> hashMap = new HashMap<String, String>();
				hashMap.put(level, code);
				threadList.add(hashMap);
				//HttpThread.createThreadPoor(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode(level,"utf-8")+"&code="+code);
				//HttpUtil.post(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode(level,"utf-8")+"&code="+code,"");
			} catch (Exception e) {
				e.printStackTrace();
			}
			params.put("level", level);
		}
		
		if(!CommonUtility.isEmpty(output)){
			carModel.setOutput(output);
			carModel.setOutputDown(outputValue - 100);
			carModel.setOutputUp(outputValue + 100);
			params.put("output", output);
			params.put("outputDown", outputValue - 100);
			params.put("outputUp", outputValue + 100);
		}
		if(!CommonUtility.isEmpty(TOrL)){
			carModel.setTOrL(TOrL);
			params.put("TOrL", TOrL);
		}
		carModel.setCarclassifyid("1");
		params.put("carclassifyid", 1);
		//List<CarModel> CarModelList1 = carModelService.getPriceData(carModel);
		
        //设置 分页参数
        PageHelper.startPage(page,limit);
    	basePath = basePath+"common/img/";
    	params.put("path", basePath);
        //调用 查询方法
        List<CarModel> CarModelList=carModelService.loadPageList(params);
        //处理数据
        PageInfo<CarModel> pageInfo=new PageInfo<CarModel>(CarModelList);
		String json = "";
        try {
            //转换 时间格式/并将数据转换成json字符串
            JsonConfig jsonConfig = JSONUtil.getJsonConfig(DateUtility.DateFormat1);
            json= JSONUtil.toLayUIJSONAll(pageInfo.getTotal(),pageInfo.getList(), jsonConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
		//查询车型分组 
		List<String> modelList = carModelService.getModel(carModel);
		ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
		for (String model : modelList) {
			HashMap<String, Object> hashMap = new HashMap<String,Object>();
			hashMap.put("model", model);
			arrayList.add(hashMap);
		}
		//查询变速箱分组
		List<String> gearboxList = carModelService.getGearbox(carModel);
		ArrayList<HashMap<String, Object>> gearboxListMap = new ArrayList<HashMap<String, Object>>();
		for (String gearbox : gearboxList) {
			HashMap<String, Object> hashMap = new HashMap<String,Object>();
			hashMap.put("gearbox", gearbox);
			gearboxListMap.add(hashMap);
		}
		//查询排量分组
		JSONObject jsonObject = new JSONObject();
		if(CarModelList.size() == 0){
			//数据为空的话返回0
			jsonObject.element("state", Constant.dataState.NoData);
		}else{
			jsonObject.element("state", Constant.dataState.HaveData);
			jsonObject.element("modelList", JSONArray.fromObject(arrayList));
			jsonObject.element("gearboxList", JSONArray.fromObject(gearboxListMap));
		}
		
		long begin = System.currentTimeMillis();
		HttpThread.createThreadPoor(threadList);
		LogUtil.info("线程执行时间是：========="+(System.currentTimeMillis() - begin)+"");
		
		HashMap<String, String> requstParamMap = new HashMap<String,String>();
		requstParamMap.put("beginPrice", beginPrice);
		requstParamMap.put("endPrice", endPrice);
		requstParamMap.put("gear",gear);
		requstParamMap.put("level", level);
		requstParamMap.put("output", output);
		requstParamMap.put("TOrL", TOrL);
		
		jsonObject.element("requstParamData", requstParamMap);
		jsonObject.element("data", json);
		//返回数据
		Gson gson=new Gson();
		response.setCharacterEncoding("utf-8");
		return gson.toJson(jsonObject);
		//return jsonObject;
	}
	
	/**
	 * @类功能说明：汽车各个功能的介绍
	 * @作者：Chenxh
	 * @创建时间：2018年11月21日上午8:50:18
	 */
	@RequestMapping("/carIntroduce")
	@ResponseBody
	public void carIntroduce(HttpServletRequest request, HttpServletResponse response){
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		//汽车分类id
		String carCategoryId = request.getParameter("carCategoryId");
		//介绍汽车的部分
		String way = request.getParameter("way");
		//机器人编号
		String code = request.getParameter("code");
		
		//请求参数
		HashMap<String, Object> requestParam = new HashMap<String,Object>();
		requestParam.put("carCategoryId", carCategoryId);
		requestParam.put("way", way);
		
		Example example = new Example(CarCategory.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carcategoryid",carCategoryId);
		//查询是哪一系列的车
		List<CarCategory> carCategoryList = carCategoryService.selectByExample(example);
		String carcategoryname = carCategoryList.get(0).getCarcategoryname();
		
		try {
			HttpUtil.post(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode("智能导购","utf-8")+"&code="+code,"");
			HttpUtil.post(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode(carcategoryname,"utf-8")+"&code="+code,"");
			//HttpThread.createThreadPoor(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode("智能导购","utf-8")+"&code="+code);
			//HttpThread.createThreadPoor(basePath+"action/lodJson/loadMess?answer="+URLEncoder.encode(carcategoryname,"utf-8")+"&code="+code);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			//外观、内饰、动力、科技、安全
			if("外观".equals(way)){
				loadMess(request, response, code, carcategoryname+"外观");
			}
			if("内饰".equals(way)){
				loadMess(request, response, code, carcategoryname+"内饰");
			}
			if("动力".equals(way)){
				loadMess(request, response, code, carcategoryname+"动力");
			}
			if("科技".equals(way)){
				loadMess(request, response, code, carcategoryname+"科技");
			}
			if("安全".equals(way)){
				loadMess(request, response, code, carcategoryname+"安全");
			}
			if("视频".equals(way)){
				loadMess(request, response, code, carcategoryname+"视频");
			}
		}  catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @类功能说明：获取首页的问题
	 * @类修改者：
	 * @修改日期：
	 * @修改说明：
	 * @公司名称：
	 * @作者：Chenxh
	 * @创建时间：2018年11月21日上午8:51:18
	 */
	@RequestMapping("/getQuestion")
	@ResponseBody
	public String getQuestion(HttpServletRequest request, HttpServletResponse response){
		String json="";
		//获得  页码数
        Integer page=CommonUtility.isEmpty(request.getParameter("page"))?1:Integer.parseInt(request.getParameter("page")+"");
        //获得 每页的行数
        Integer limit=CommonUtility.isEmpty(request.getParameter("limit"))?10:Integer.parseInt(request.getParameter("limit")+"");
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        params.put("limit", limit);
        
        //设置 分页参数
        PageHelper.startPage(page,limit);
        //调用 查询方法
        List<CarQuestion> carQuestionList=carQuestionService.loadPageList(params);
        //处理数据
        PageInfo<CarQuestion> pageInfo=new PageInfo<CarQuestion>(carQuestionList);
        try {
            //转换 时间格式/并将数据转换成json字符串
            JsonConfig jsonConfig = JSONUtil.getJsonConfig(DateUtility.DateFormat1);
            json= JSONUtil.toLayUIJSONAll(pageInfo.getTotal(),pageInfo.getList(), jsonConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
        response.setCharacterEncoding("utf-8");
        return json;
	}
	
	/**
	 * @类功能说明：汽车竞品参数的接口
	 * @类修改者：
	 * @修改日期：
	 * @修改说明：
	 * @公司名称：
	 * @作者：Chenxh
	 * @创建时间：2018年11月22日下午5:28:59
	 */
	@RequestMapping("/carCompetitive")
	@ResponseBody
	public List<CarCompetitiveDetail> carCompetitive(HttpServletRequest request, HttpServletResponse response){
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//本地汽车车系名称
		String carCategoryName = request.getParameter("carCategoryName");
		
		//竞品汽车车系名称
		String competitiveCategoryName = request.getParameter("competitiveCategoryName");
		
		Example example = new Example(CarCompetitive.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("categoryname",carCategoryName);
		createCriteria.andEqualTo("competitivecategoryname",competitiveCategoryName);
		List<CarCompetitive> carCompetitiveList = carCompetitiveService.selectByExample(example);
		
		List<CarCompetitiveDetail> carCompetitiveDetailList = new ArrayList<CarCompetitiveDetail>();
		if(carCompetitiveList.size()!=0){
			CarCompetitive carCompetitive = carCompetitiveList.get(0);
			Integer id = carCompetitive.getId();
			
			Example example2 = new Example(CarCompetitiveDetail.class);
			Criteria createCriteria2 = example2.createCriteria();
			
			createCriteria2.andEqualTo("competitiveid",id);
			carCompetitiveDetailList = carCompetitiveDetailService.selectByExample(example2);
		}
		
		return carCompetitiveDetailList;
	}
	
	
	/**
	 * @类功能说明：汽车的竞品列表
	 * @作者：Chenxh
	 * @创建时间：2018年11月22日下午5:28:59
	 */
	@RequestMapping("/getCarCompetitive")
	@ResponseBody
	public List<CarCompetitive> getCarCompetitive(HttpServletRequest request, HttpServletResponse response){
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//本地汽车车系名称
		String carCategoryName = request.getParameter("carCategoryName");
		/*
		//竞品汽车车系名称
		String competitiveCategoryName = request.getParameter("competitiveCategoryName");*/
		
		Example example = new Example(CarCompetitive.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("categoryname",carCategoryName);
		List<CarCompetitive> carCompetitiveList = carCompetitiveService.selectByExample(example);
		
		return carCompetitiveList;
	}
	
	
	/**
	 * @类功能说明：查询各个表中的汽车详情的信息
	 * @作者：Chenxh
	 * @创建时间：2018年10月25日下午2:02:12
	 */
	@RequestMapping("/getCarModelDetail")
	@ResponseBody
	private String getCarModelDetail(HttpServletRequest request, String carmodelid,HttpServletResponse resp) {
		
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//获取所有的汽车详情信息
		//Map<String, Object> carDetailInfo = carDetailBaseInfoService.getInfoByCarmodelId(carmodelid);
		HashMap<String, Object> dataMap = new HashMap<String,Object>();
		//车详情基本信息
		List<CarDetailBaseInfo> carDetailBaseInfo = getCarDetailBaseInfo(carmodelid);
		dataMap.put("carDetailBase", carDetailBaseInfo);
		//汽车车身详情
		List<CarDetailBody> carDetailBody = carDetailBody(carmodelid);
		dataMap.put("carDetailBody", carDetailBody);
		//汽车发动机详情
		List<CarDetailEngine> carDetailEngine = carDetailEngine(carmodelid);
		dataMap.put("carDetailEngine", carDetailEngine);
		//汽车变速箱详情
		List<CarDetailChangeSpeedCase> carDetailChangeSpeedCase = carDetailChangeSpeedCase(carmodelid);
		dataMap.put("carDetailChangeSpeedCase", carDetailChangeSpeedCase);
		//汽车底盘转向详情
		List<CarDetailChassisTurn> carDetailChassisTurn = carDetailChassisTurn(carmodelid);
		dataMap.put("carDetailChassisTurn", carDetailChassisTurn);
		//汽车车轮制动详情
		List<CarDetailWheelBrake> carDetailWheelBrake = carDetailWheelBrake(carmodelid);
		dataMap.put("carDetailWheelBrake", carDetailWheelBrake);
		//汽车安全装备详情
		List<CarDetailSafetyEquipment> carDetailSafetyEquipment = carDetailSafetyEquipment(carmodelid);
		dataMap.put("carDetailSafetyEquipment", carDetailSafetyEquipment);
		//汽车操控配置详情
		List<CarDetailControlConfig> carDetailControlConfig = carDetailControlConfig(carmodelid);
		dataMap.put("carDetailControlConfig", carDetailControlConfig);
		//汽车外部配置详情
		List<CarDetailOutConfig> carDetailOutConfig = carDetailOutConfig(carmodelid);
		dataMap.put("carDetailOutConfig", carDetailOutConfig);
		//汽车内部配置详情
		List<CarDetailInConfig> carDetailInConfig = carDetailInConfig(carmodelid);
		dataMap.put("carDetailInConfig", carDetailInConfig);
		//汽车坐位配置详情
		List<CarDetailSeatConfig> carDetailSeatConfig = carDetailSeatConfig(carmodelid);
		dataMap.put("carDetailSeatConfig", carDetailSeatConfig);
		//汽车多媒体配置详情
		List<CarDetailMediaConfig> carDetailMediaConfig = carDetailMediaConfig(carmodelid);
		dataMap.put("carDetailMediaConfig", carDetailMediaConfig);
		//汽车灯光配置详情
		List<CarDetailLightConfig> carDetailLightConfig = carDetailLightConfig(carmodelid);
		dataMap.put("carDetailLightConfig", carDetailLightConfig);
		//汽车玻璃后视镜详情
		List<CarDetailGlassMirror> carDetailGlassMirror = carDetailGlassMirror(carmodelid);
		dataMap.put("carDetailGlassMirror", carDetailGlassMirror);
		//汽车空调冰箱信息
		List<CarDetailConditionRefrigerator> carDetailConditionRefrigerator = carDetailConditionRefrigerator(carmodelid);
		dataMap.put("carDetailConditionRefrigerator", carDetailConditionRefrigerator);
		//汽车高科技信息
		List<CarDetailHighTech> carDetailHighTech = carDetailHighTech(carmodelid);
		dataMap.put("carDetailHighTech", carDetailHighTech);
		
		Gson gson = new Gson();
		String json = gson.toJson(dataMap);
		json = json.replace("\\u0026nbsp;", "");
		json = json.replace("/\\u0026nbsp;", "");
		LogUtil.info(json);
		resp.setCharacterEncoding("utf-8");
		return json;
	}
	
	
	/**
	 * @类功能说明：汽车优惠
	 * @作者：Chenxh
	 * @创建时间：2018年10月27日上午10:33:57
	 */
	@RequestMapping("/carDiscount")
	public void carDiscount(HttpServletRequest request,HttpServletResponse response){
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//系列id
		String carCategoryId = request.getParameter("carCategoryId");
		Map<String,Object> map = new HashMap<String,Object>();
		//根据车系查询贷款方案
		Example example2 = new Example(CarLoan.class);
		Criteria createCriteria2 = example2.createCriteria();
		createCriteria2.andEqualTo("carcategoryid",carCategoryId);
		List<CarLoan> CarLoanList = carLoanService.selectByExample(example2);
		
		//查询车系名称
		Example example = new Example(CarCategory.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carcategoryid",carCategoryId);
		List<CarCategory> carCategoryList = carCategoryService.selectByExample(example);
		
		if(CarLoanList.size()!=0){
			//查询指导价区间和图片
			Map<String,Object> carInfoMap = carModelService.getPriceBetween(request,carCategoryId);
			//贷款金额
			BigDecimal money = new BigDecimal(CarLoanList.get(0).getMoney());
			//期限
			BigDecimal monthnum = new BigDecimal(CarLoanList.get(0).getMonthnum());
			//月供
			BigDecimal monthnumMoney = money.divide(monthnum,2,BigDecimal.ROUND_HALF_UP);

			map.put("carCategoryName",carCategoryList.get(0).getCarcategoryname());
			map.put("money",money);
			map.put("monthnum",monthnum);
			map.put("monthnumMoney",monthnumMoney);
			
			map.put("minPrice",carInfoMap.get("minPrice"));
			map.put("maxPrice",carInfoMap.get("maxPrice"));
			map.put("img",carInfoMap.get("img"));
			//map.put("speak", "已为您找到"+carCategoryList.get(0).getCarcategoryname()+"优惠方案，贷"+money+"元，"+monthnum+"个月零利息，月供"+monthnumMoney+"元就能取走车");
		}
		GsonBuilder gb= new GsonBuilder();
		gb.disableHtmlEscaping();
		String json = gb.create().toJson(map);
		System.out.println(json);
		try {
			super.ajaxOutput(response, JSON.toJSONString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @return 
	 * @类功能说明：获取主界面的汽车优惠
	 * @作者：Chenxh
	 * @创建时间：2018年12月1日下午2:38:01
	 */
	@RequestMapping("/getcarDiscount")
	@ResponseBody
	public HashMap<String, String> getcarDiscount(HttpServletRequest request,HttpServletResponse response){
		
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//机器人编码
		String robotCode = request.getParameter("robotCode");
		//根据机器人编码获取汽车优惠
		CarDiscount carDiscount= carDiscountService.getcarDiscountByRobotCode(robotCode);
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    	basePath = basePath+"common/img/";
    	
    	HashMap<String, String> hashMap = new HashMap<String,String>();
		if(carDiscount!=null){
			String firstimg = carDiscount.getFirstimg();
			String secondimg = carDiscount.getSecondimg();
			String thirdimg = carDiscount.getthirdimg();
			
			hashMap.put("id", carDiscount.getId().toString());
			hashMap.put("firstimg", basePath+firstimg);
			hashMap.put("secondimg", basePath+secondimg);
			hashMap.put("thirdimg", basePath+thirdimg);
		}else{
			hashMap.put("id", "");
			hashMap.put("firstimg", "");
			hashMap.put("secondimg", "");
			hashMap.put("thirdimg", "");
		}
		return hashMap;
		
	}
	
	
	/**
	 * @return 
	 * @类功能说明：获取主界面的汽车优惠
	 * @作者：Chenxh
	 * @创建时间：2018年12月1日下午2:38:01
	 */
	@RequestMapping("/getcarDiscountDetail")
	@ResponseBody
	public HashMap<String, String> getcarDiscountDetail(HttpServletRequest request,HttpServletResponse response){
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		HashMap<String, Object> hashMap2 = new HashMap<String,Object>();
		String discountId = request.getParameter("id");
		hashMap2.put("discountId", discountId);
		String wantImg = request.getParameter("wantImg");
		
		if("firstimg".equals(wantImg)){
			hashMap2.put("str", "firstimgsmall");
			hashMap2.put("test", "firsttext");
		}
		
		if("secondimg".equals(wantImg)){
			hashMap2.put("str", "secondimgsmall");
			hashMap2.put("test", "secondtext");
		}
		
		if("thirdimg".equals(wantImg)){
			hashMap2.put("str", "thirdimgsmall");
			hashMap2.put("test", "thirdtext");
		}
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    	basePath = basePath+"common/img/";
		HashMap<String, String> resultMap= carDiscountDetailService.getDataByMap(hashMap2);
		resultMap.put("img", basePath+resultMap.get("img"));
		return resultMap;
		
	}
	
	/**
	 * @类功能说明：汽车配置详情
	 * @作者：Chenxh
	 * @创建时间：2018年10月25日上午11:15:20
	 */
	@RequestMapping("/carDetail")
	public void carDetailCatagory(HttpServletRequest request, HttpServletResponse response){
		StringBuffer requestURL = request.getRequestURL();
		String queryString = request.getQueryString(); 
		try {
			LogUtil.info(requestURL+URLDecoder.decode(queryString,"utf-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//车类别
		Object carCategory =  request.getParameter("carCategoryId");
		//车年份
		Object year =  request.getParameter("year");
		//车型别名
		Object otherName1 =  request.getParameter("model");
		
		HashMap<String, Object> map = new HashMap<String,Object>(); 	
		CarModel carModel = new CarModel();
		if(!CommonUtility.isEmpty(carCategory)){
			carModel.setCarcategoryid(carCategory.toString());
		}
		if(!CommonUtility.isEmpty(year)){
			carModel.setCaryear(year.toString());
		}
		if(!CommonUtility.isEmpty(otherName1)){
			/*carModel.setCarCategoryName(model.toString());*/
			carModel.setOtherName(otherName1.toString());
		}
		carModel.setCarclassifyid("1");
		List<CarModel> carModelList = carModelService.getPriceData(carModel,request);
		map.put("carModelList",carModelList);
		
		GsonBuilder gb= new GsonBuilder();
		gb.disableHtmlEscaping();
		String json = gb.create().toJson(map);
		System.out.println(json);
		try {
			super.ajaxOutput(response, JSON.toJSONString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	
	
	
	/** 
	 * @类功能说明：车详情基本信息
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailBaseInfo> getCarDetailBaseInfo(String carmodelid){
		Example example = new Example(CarDetailBaseInfo.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailBaseInfoService.selectByExample(example);
	}

	/**
	 * @类功能说明：汽车车身详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailBody> carDetailBody(String carmodelid){
		Example example = new Example(CarDetailBody.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailBodyService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车发动机详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailEngine> carDetailEngine(String carmodelid){
		Example example = new Example(CarDetailEngine.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailEngineService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车变速箱详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailChassisTurn> carDetailChassisTurn(String carmodelid){
		Example example = new Example(CarDetailChassisTurn.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailChassisTurnService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车变速箱详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailChangeSpeedCase> carDetailChangeSpeedCase(String carmodelid){
		Example example = new Example(CarDetailChangeSpeedCase.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailChangeSpeedCaseService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车车轮制动详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailWheelBrake> carDetailWheelBrake(String carmodelid){
		Example example = new Example(CarDetailWheelBrake.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailWheelBrakeService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车安全装备详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailSafetyEquipment> carDetailSafetyEquipment(String carmodelid){
		Example example = new Example(CarDetailSafetyEquipment.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailSafetyEquipmentService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车操控配置详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailControlConfig> carDetailControlConfig(String carmodelid){
		Example example = new Example(CarDetailControlConfig.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailControlConfigService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车外部配置详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailOutConfig> carDetailOutConfig(String carmodelid){
		Example example = new Example(CarDetailOutConfig.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailOutConfigService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车内部配置详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailInConfig> carDetailInConfig(String carmodelid){
		Example example = new Example(CarDetailInConfig.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailInConfigService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车坐位配置详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailSeatConfig> carDetailSeatConfig(String carmodelid){
		Example example = new Example(CarDetailSeatConfig.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailSeatConfigService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车多媒体配置详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailMediaConfig> carDetailMediaConfig(String carmodelid){
		Example example = new Example(CarDetailMediaConfig.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailMediaConfigService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车灯光配置详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailLightConfig> carDetailLightConfig(String carmodelid){
		Example example = new Example(CarDetailLightConfig.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailLightConfigService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车灯光配置详情
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailGlassMirror> carDetailGlassMirror(String carmodelid){
		Example example = new Example(CarDetailLightConfig.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailGlassMirrorService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车空调冰箱信息
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailConditionRefrigerator> carDetailConditionRefrigerator(String carmodelid){
		Example example = new Example(CarDetailConditionRefrigerator.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailConditionRefrigeratorService.selectByExample(example);
	}
	/**
	 * @类功能说明：汽车高科技信息
	 * @作者：Chenxh
	 * @创建时间：2018年11月30日上午10:08:12
	 */
	public List<CarDetailHighTech> carDetailHighTech(String carmodelid){
		Example example = new Example(CarDetailHighTech.class);
		Criteria createCriteria = example.createCriteria();
		createCriteria.andEqualTo("carmodelid",carmodelid);
		return carDetailHighTechService.selectByExample(example);
	}
	
	public void loadMess(HttpServletRequest request, HttpServletResponse response,String code,String question){
		this.innitData();
		String json = "";
		this.msgType = 1;
		RobotInfo robotInfo = robotInfoService.loadByCode(code);
		System.out.println(question);
		//获得匹配到的集合
		List<Map<String,Object>> list = skillsOptionService.LoadSkills(question, robotInfo.getId());
		if(list != null && list.size() == 1){
			Map<String,Object> map = list.get(0);
			skill = Integer.parseInt(map.get("skillid")+"");
			scene = Integer.parseInt((CommonUtility.isEmpty(map.get("type"))?"0":map.get("type"))+"");
			SkillsOption option = null;
			Map<String, Object> cmdMap = new HashMap<String, Object>();
			option = skillsOptionService.loadById(Integer.parseInt(map.get("optionid")+""));
			/*speak = option.getContents();
			if(option.getNettype() == 0){
				//内网链接需要配置路径
				if(!StringUtil.isEmpty(option.getUrl())){
					url = sysVarsService.loadUrlByName(ComUtil.SYSTEM_PATH) +
							sysVarsService.loadUrlByName(ComUtil.SYSINFO_VIRTUALPATH) +
							sysVarsService.loadUrlByName(ComUtil.HTML_PATH) +
							option.getUrl();
				}
			}else{
				//外网路径直接等于
				url = option.getUrl();
			}*/
			cmdMap = skillsOptionService.loadByCmd(option.getId());
			Map<String,Object> resultMap = new HashMap<String,Object>();

			resultMap.put("scene", this.scene);
			resultMap.put("skill", this.skill);
			resultMap.put("msgType", this.msgType);
			resultMap.put("flag", flag);
			resultMap.put("msg", msg);
			resultMap.put("speak",speak);
			resultMap.put("skillList", new Object[]{});
			resultMap.put("url",url);
			resultMap.put("set", cmdMap);
			json = JSON.toJSONString(resultMap);

			super.ajaxOutput(response, json);
		}else if(list!=null && list.size()>1){
			//组织集合返回
			List<Map<String,Object>> resultlist=new ArrayList<Map<String,Object>>();
			for(Map<String,Object> obj:list){
				Map<String,Object> objMap=new HashMap<String,Object>();
				objMap.put("title", obj.get("title"));
				objMap.put("skillId",obj.get("skillid"));
				resultlist.add(objMap);
			}
			Map<String,Object> resultMap = new HashMap<String,Object>();
			resultMap.put("scene", this.scene);
			resultMap.put("skill", this.skill);
			resultMap.put("msgType", this.msgType);
			resultMap.put("flag", flag);
			resultMap.put("msg", msg);
			speak = "已为您找到相关业务，请问你要办理第几项？";
			resultMap.put("speak", speak);
			resultMap.put("skillList", resultlist);
			resultMap.put("url",url);
			resultMap.put("set", new Object());
			json=JSON.toJSONString(resultMap);
			
			ajaxOutput(response, json);
			
		}else{
			//未匹配到数据转发到基础问答处理
				this.loadSoundQuAn(request, response);
		}
				
	}
	
	/**
	 * 匹配基础问答
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/loadSoundQuAn")
	public void loadSoundQuAn(HttpServletRequest request, HttpServletResponse response){
		this.innitData();
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("skill", 0);
		resultMap.put("scene",0);
		resultMap.put("msgType",2);
		Map<String, Object> cmdMap = new HashMap<String, Object>();	//命令集集合
		List<Map<String,Object>> objectList = new ArrayList<Map<String,Object>>(); //匹配项
		// 问题
		String answer =String.valueOf(request.getAttribute("answer"));
		try {
			// 机器人编码
			String code = request.getParameter("code");
			// 根据编码获取机器人
			RobotInfo robot = robotInfoService.loadByCode(code);
			
			// 匹配最多的次数
			int maxNum = 0;
			//通过机器人查询
			List<SoundQu>  soundList=soundQuService.loadByCode(code);
			SoundQu soundQu = this.getByQuestionsByQustion(soundList,answer);
			if(ObjectUtil.isNull(soundQu)){
				// 获取机器人机构编码
				int orgId = 0;
				if(!CommonUtility.isEmpty(robot.getOrg())){
					orgId = robot.getOrg();
				}
				soundList=soundQuService.loadAllByOrg(orgId);
				soundQu = this.getByQuestionsByQustion(soundList,answer);
				
			}
			
			if(!CommonUtility.isEmpty(soundQu) && !CommonUtility.isEmpty(soundQu.getFlg()) && soundQu.getFlg()==1){
				resultMap.put("msgType",1);
			}
			
				// 找到最大匹配项
			if(!ObjectUtil.isNull(soundQu)){

				List<Map<String, Object>> lsq = soundQuAnService.loadByQu(soundQu.getId());
				if(!ObjectUtil.isNull(lsq) && lsq.size() > 0){
					int num = lsq.size();
					Random random = new Random();
					// 随机选择一个答案
					num = random.nextInt(num);
					Map<String, Object> sqa = lsq.get(num);
					this.speak = String.valueOf(sqa.get("contents"));
					this.status = 1;
					if(!ObjectUtil.isNull(sqa.get("url")) && !ObjectUtil.isEmpty(sqa.get("url"))){
						this.url = sysVarsService.findByName(ComUtil.SYSTEM_PATH).getValues()+ 
								   sysVarsService.findByName(ComUtil.SYSINFO_VIRTUALPATH).getValues()+
								   sysVarsService.findByName(ComUtil.HTML_PATH).getValues() + sqa.get("url");
					}
					// 绑定命令集ID
					int cmdId = ObjectUtil.isNull(sqa.get("collection"))?0:Integer.parseInt(String.valueOf(sqa.get("collection")));
					if(cmdId > 0){
						String mapUrl = sysVarsService.findByName(ComUtil.SYSTEM_PATH).getValues()+ 
								        sysVarsService.findByName(ComUtil.SYSINFO_VIRTUALPATH).getValues()+
								        sysVarsService.findByName(ComUtil.MAP_PATH).getValues();
						
						// 获取命令集
						cmdMap = cmdCollectionService.loadCmdMap(cmdId, mapUrl);
					}
					
				}else{
						this.flag = 1;
						this.msg = "暂无消息";
						this.status = 2;
//					}
				}
				
			}else{
					request.getRequestDispatcher("/action/lodJson/chat").forward(request, response);
			}
				
			
		} catch (Exception e) {
			e.printStackTrace();
			this.flag = 2;
			this.msg = "返回数据失败！";
			this.status=0;
			
		}
		resultMap.put("flag", this.flag);
		resultMap.put("set", cmdMap);
		resultMap.put("speak",this.speak);
		resultMap.put("msg", this.msg);
		resultMap.put("url", this.url);
		resultMap.put("skillList", objectList);
		
		String json = JSON.toJSONString(resultMap);
		super.ajaxOutput(response, json);
	}

	/**
	 * 
	 * @param soundList
	 * @param qeustion
	 * @return
	 */
	public static SoundQu getByQuestionsByQustion(List<SoundQu>  soundList,String qeustion){
		int length=0;
		SoundQu soundQu = null;
		if(!ObjectUtil.isNull(soundList) && soundList.size() > 0){
			for(SoundQu sq : soundList){
				if(ObjectUtil.isNull(sq) || StringUtil.isTrimEmpty(sq.getKeywords())){
					continue;
				}
				String keyWords=sq.getKeywords().replaceAll("，", ",");
				String[] keywords = keyWords.split(",");
				StringBuffer str = null;
				if(!ObjectUtil.isNull(keywords) && keywords.length>0){
					str = new StringBuffer("(");
					int objLength = keywords.length;
					
					for(int i=0;i<objLength;i++){
						str.append(keywords[i]);
						if(i<objLength-1){
							str.append("|");
						}
					}
					str.append(")");
					if(StringUtils.checkRegular(str.toString(), qeustion)){
						String objString=StringUtils.getStringValue(str.toString(), qeustion);
						if(objString.length()>length){
							soundQu=sq;
							length=objString.length();
						}
						
					}
				}
				
			}
			
		}
		return soundQu;
	}
	
	/**
	 * 将返回参数重置
	 */
	private void innitData(){
		url = "";
		msgType = 2; // 2默认 1.场景模式 2.对答模式 
		msg="返回成功";	//日志说明
		flag = 0; // 返回标志
		scene=0;	//场景类型
		skill=0;
		this.speak="";
		this.status=1;
	}
	
}
